/**  
 * @Title: tt.java
 * @Description: TODO(描述)
 * @author liuyi
 * @date 2023-11-24 14:47:11 
 */  
package com.fsxgt.datagrid.sys.utils;

import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import com.fsxgt.datagrid.sys.bo.AuthorityBO;
import com.fsxgt.datagrid.sys.bo.SysUserBO;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})

        }
        
		)
public class UserParametersInterceptor implements Interceptor {
 
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        Object params = args[1];
        if(params==null) {
        	Map map = new HashMap();
            map.put("curUser", getCurUser());
            invocation.getArgs()[1] = map;
        }else if (params instanceof AuthorityBO) {
        	AuthorityBO authorityBO = (AuthorityBO) params;
        	authorityBO.setCurUser(getCurUser());
        } else if (params instanceof MapperMethod.ParamMap) {
            MapperMethod.ParamMap<Object> map = (MapperMethod.ParamMap) params;
            map.put("curUser", getCurUser());
        }
        return invocation.proceed();
    }
 
    /**
     * 获取当前登录用户ID
     *
     * @return 用户ID
     */
    private SysUserBO getCurUser() {
        try {
            return LoginHelper.getCurUser();
        } catch (Exception ignored) {
            return null;
        }
    }
}
